import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'dva';
import { Link, Route } from 'dva/router';
import DocumentTitle from 'react-document-title';
import GlobalFooter from '../../components/GlobalFooter';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Service.less';
import {getRouteData} from '../../utils/utils';
import ServiceList from '../../components/service/index';
import ServiceEdit from '../../components/service/ServiceEdit';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Button,
    Modal,
    message
} from 'antd';

const FormItem = Form.Item;
const {Option} = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

@connect(state => ({
    rule: state.service
}))
@Form.create()
class Service extends React.PureComponent {

    state = {
        modalVisible: false,
        editType: 'add',
        formValues: {},
        record: {},
        selectedRows: [],
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({
            type: 'service/fetch',
        });
    }

    handleSearch = (e) => {
        e.preventDefault();

        const {dispatch, form} = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err) return;

            const values = {
                ...fieldsValue,
                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
            };

            this.setState({
                formValues: values,
            });

            dispatch({
                type: 'service/fetch',
                payload: values,
            });
        });
    }

    handleFormReset = () => {
        const {form, dispatch} = this.props;
        form.resetFields();
        dispatch({
            type: 'service/fetch',
            payload: {},
        });
        this.setState({
            formValues:{},
        })
    }

    handleServiceListChange = (pagination, filtersArg, sorter) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;

        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = {...obj};
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});

        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formValues,
            ...filters,
        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'service/fetch',
            payload: params,
        });
    }

    handleAddService = () => {
        this.handleModalVisible(true);
        this.setState({
            editType: 'add',
        });
    }

    handleSynApiCacheToDb = () => {
        const {dispatch} = this.props;
        dispatch({
            type: 'service/synApiCacheToDb',
            callback: (response) => {
                if (response.result === 0) {
                    message.success('缓存同步到数据库成功');
                } else {
                    message.success('操作失败');
                }
            }
        });
    }

    handleSynApiDbToCache = () => {
        const {dispatch} = this.props;
        dispatch({
            type: 'service/synApiDbToCache',
            callback: (response) => {
                if (response.result === 0) {
                    message.success('数据库同步到缓存成功');
                } else {
                    message.success('操作失败');
                }
            }
        });
    }
    handleDelCache = () => {
        const {dispatch} = this.props;
        dispatch({
            type: 'service/delCache',
            callback: (response) => {
                if (response.result === 0) {
                    message.success('清空缓存成功');
                } else {
                    message.success('操作失败');
                }
            }
        });
    }
    handleEditServiceRow = (record, pagination) => {
        this.handleModalVisible(true);
        this.setState({
            editType: 'mod',
            record: record
        });
    }

    handleDelServiceRow = (serviceId, pagination) => {
        const {dispatch} = this.props;
        dispatch({
            type: 'service/del',
            payload: {service_id: serviceId},
            callback: (response) => {
                if (response.result === 0) {
                    message.success('删除成功');
                    this.handleModalSuccess(pagination);
                } else {
                    message.success('删除失败');
                }
            }
        });
    }

    handleModalVisible = (flag) => {
        this.setState({
            modalVisible: !!flag,
        });
    }

    handleModalSuccess = (pagination) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;
        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formValues,
        };
        dispatch({
            type: 'service/fetch',
            payload: params,
        });
    }

    renderSimpleForm() {
        const {getFieldDecorator} = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
              <Row gutter={{md: 8, lg: 24, xl: 48}}>
                <Col md={8} sm={24}>
                  <FormItem label="服务名称">
                      {getFieldDecorator('service_name')(
                          <Input placeholder="请输入"/>
                      )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <FormItem label="状态">
                      {getFieldDecorator('service_status')(
                          <Select placeholder="请选择" style={{width: '100%'}}>
                            <Option value="">请选择</Option>
                            <Option value="0">不可用</Option>
                            <Option value="1">可用</Option>
                          </Select>
                      )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                        <span className={styles.sumbitButtons}>
                          <Button type="primary" htmlType="submit">查询</Button>
                          <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>重置</Button>
                        </span>
                </Col>
              </Row>
            </Form>
        );
    }

    renderForm() {
        return this.renderSimpleForm();
    }

    render() {
      const {modalVisible, editType, record, selectedRows} = this.state;
      const {rule: {loading: ruleLoading, data}} = this.props;
      console.log(data);
      return (
          <div style={{marginTop:'50px'}}>
          <PageHeaderLayout title="服务接口管理" >
            <Card bordered={false}>
              <div className={styles.tableList}>
                <div className={styles.tableListForm}>
                    {this.renderForm()}
                </div>
                <div className={styles.tableListOperator}>
                    <Button icon="plus" type="primary" onClick={() => this.handleAddService()}>新建</Button>
                    <Button type="primary" onClick={() => this.handleSynApiCacheToDb()}>缓存同步到数据库</Button>
                    <Button type="primary" onClick={() => this.handleSynApiDbToCache()}>数据库同步到缓存</Button>
                    <Button type="primary" onClick={() => this.handleDelCache()}>api缓存清空</Button>
                </div>
                <ServiceList
                    selectedRows={selectedRows}
                    loading={ruleLoading}
                    data={data}
                    onSelectRow={this.handleSelectRows}
                    onChange={this.handleServiceListChange}
                    onDelRow={this.handleDelServiceRow}
                    onEditRow={this.handleEditServiceRow}
                />
              </div>
            </Card>
              <Modal
                  title={editType === 'add' ? '新增服务接口' :'编辑服务接口'}
                  key={new Date()}
                  visible={modalVisible}
                  onOk={this.handleAdd}
                  onCancel={() => this.handleModalVisible()}
                  footer={null}
                  width={800}
              >
                  <ServiceEdit  ref="serviceEdit"
                                  pagination={data.pagination}
                                  editType={editType}
                                  record={record}
                                  handleModalVisible={this.handleModalVisible}
                                  handleModalSuccess={this.handleModalSuccess}/>
              </Modal>
          </PageHeaderLayout>
          </div>
      );
    }
}

export default Service;
